package org.diysearch.tools;

import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.diysearch.interfaces.TemplateEngine;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreeMarkerTemplateEngine implements TemplateEngine {

	static Configuration config;
	Template template;
	String fpath = null;
	String loader = null;
	Map<String, Object> finalContent;

	Log LOG = LogFactory.getLog(FreeMarkerTemplateEngine.class);

	public FreeMarkerTemplateEngine() {
		finalContent = new HashMap<String, Object>();
	}

	public Writer getContent(String template, Map<String, Object> content)
			throws Exception {
		StringWriter sw = new StringWriter();

		try {
			if (config == null)
				config = (Configuration) BaseTool.IOC_ENGINE
						.getBean("freemarkerConfig");

			BeansWrapper bw = new BeansWrapper();
			bw.setExposureLevel(bw.EXPOSE_ALL);
			config.setObjectWrapper(bw);

			try {
				this.template = config.getTemplate(template);
			} catch (Exception ex) {
				throw new Exception("Template not found "
						+ StringTools.getStackTrace(ex));
			}

			setContent(content);

			this.template.process(finalContent, sw);
		} catch (Exception ex) {
			throw new Exception("EXCEPTION: " + StringTools.getStackTrace(ex));
		}

		return sw;

	}

	public void setContent(Map<String, Object> content) {
		if (finalContent == null) {
			finalContent = new HashMap<String, Object>();
		}
		for (String key : content.keySet()) {
			finalContent.put(key, content.get(key));
		}

	}

	public void setContent(String symbol, Object content) {
		finalContent.put(symbol, content);
	}

	public Map<String, Object> getFinalContent() {
		return finalContent;
	}

	public void setFinalContent(Map<String, Object> finalContent) {
		this.finalContent = finalContent;
	}

}
